/**
 * Created by acer on 2015/7/22.
 */
var totalValidData;


$(document).ready(function(){
    $("#form").steps({
        bodyTag: "fieldset",
        labels: {
            current: "当前流程 :",
            pagination: "Pagination",
            finish: "完成",
            next: "下一步",
            previous: "上一步",
            loading: "加载中 ..."
        },
        enableCancelButton: 0,
        enableKeyNavigation: 0,
        enableFinishButton: 0,
        onStepChanging: function (event, currentIndex, newIndex)
        {
            var validData
            if(currentIndex==0){
                var checkInput=new Array()
                $('.i-checks').each(function(e){
                    if($(this).find('input').is(':checked')==true){
                        var thisInputID=$(this).find('input').attr('id')
                        checkInput.push(thisInputID)
                    }
                })
                if(checkInput.length>1){
                    alert('不可选择多个订单')
                }
                else if(checkInput.length==1){
                    for(var i in totalValidData){
                        if(checkInput[0]==totalValidData[i]._id){
                            lastValidData=validData=totalValidData[i]
                        }
                    }
                    $('.searchGroupSecond').each(function(e){
                        $('.search-hasResult-return').show()
                        var thisInputID=$(this).attr('id').replace('NeverSecond','')
                        for(var i in validData){
                            if(thisInputID==i){
                                $(this).val(validData[i])
                            }
                        }
                    })
                    $('.searchGroupThird').each(function(e){
                        var thisInputID=$(this).attr('id').replace('NeverThird','')
                        for(var i in validData){
                            if(thisInputID==i){
                                $(this).val(validData[i])
                            }
                        }
                    })
                    $('#snNoTemplate').html('')
                    $('#snNoTemplateEnsure').html('')
                    for(var j in validData.FDEVICELIST){
                        if(!validData.FDEVICELIST[j].FCHECKEDSTATUS){
                            validData.FDEVICELIST[j].FCHECKEDSTATUS=''
                        }
                        var snNoTemplate='<div class="form-group"><div class="col-lg-2 returnIndexName">SN号码:</div><div class="col-lg-5"><input name="searchName" type="text" class="form-control justShow" disabled="disabled" value="'+validData.FDEVICELIST[j].FSN+'"></div><div class="col-lg-2 returnIndexName">状态:</div><div class="col-lg-3"><select onchange="changeSNSituation(this)"  name="" class="form-control"'+validData.FDEVICELIST[j].FCHECKEDSTATUS+'  id="'+validData.FDEVICELIST[j].FSN+'SNSecond'+'"><option value="">请选择</option><option value="完好">完好</option><option value="屏幕损坏">屏幕损坏</option><option value="丢失">丢失</option><option value="继续使用">继续使用</option></select></div></div>'
                        var snNoTemplateEnsure='<div class="form-group"><div class="col-lg-2 returnIndexName">SN号码:</div><div class="col-lg-5"><input name="searchName" type="text" class="form-control justShow" disabled="disabled" value="'+validData.FDEVICELIST[j].FSN+'"></div><div class="col-lg-2 returnIndexName">状态:</div><div class="col-lg-3"><select name="" class="form-control" disabled="disabled"'+validData.FDEVICELIST[j].FCHECKEDSTATUS+' id="'+validData.FDEVICELIST[j].FSN+'SNThird'+'"><option value="">请选择</option><option value="完好">完好</option><option value="屏幕损坏">屏幕损坏</option><option value="丢失">丢失</option><option value="继续使用">继续使用</option></select></div></div>'
                        $('#snNoTemplate').append(snNoTemplate)
                        $('#snNoTemplateEnsure').append(snNoTemplateEnsure)
                    }
                    var form = $(this);

                    // Disable validation on fields that are disabled or hidden.
                    form.validate().settings.ignore = ":disabled,:hidden";

                    // Start validation; Prevent going forward if false
                    return form.valid();
                }
                else{
                    alert('请选择订单')
                }

            }
            else if(currentIndex==1&&newIndex>currentIndex){
                deviceListArray=lastValidData.FDEVICELIST.slice()
                for(var n in deviceListArray){
                    deviceListArray[n]['FCHECKEDSTATUS']=$('#'+deviceListArray[n].FSN+'SNSecond').val()
                }
                var form = $(this);

                // Disable validation on fields that are disabled or hidden.
                form.validate().settings.ignore = ":disabled,:hidden";

                // Start validation; Prevent going forward if false
                return form.valid();
            }
            else{
                return true;
            }
        },
        onStepChanged: function (event, currentIndex, priorIndex)
        {
            // Suppress (skip) "Warning" step if the user is old enough.
            if (currentIndex === 2 && Number($("#age").val()) >= 18)
            {
                $(this).steps("next");
            }

            // Suppress (skip) "Warning" step if the user is old enough and wants to the previous step.
            if (currentIndex === 2 && priorIndex === 3)
            {
                $(this).steps("previous");
            }
        },
        onFinishing: function (event, currentIndex)
        {
            var form = $(this);

            // Disable validation on fields that are disabled.
            // At this point it's recommended to do an overall check (mean ignoring only disabled fields)
            form.validate().settings.ignore = ":disabled";

            // Start validation; Prevent form submission if false
            return form.valid();
        },
        onFinished: function (event, currentIndex)
        {
            var form = $(this);

            // Submit form input
            form.submit();
        }
    }).validate({
        errorPlacement: function (error, element)
        {
            element.before(error);
        },
        rules: {
            confirm: {
                equalTo: "#password"
            }
        }
    });
    //try{
    //    $('.timeAccurate').datepicker({
    //        minView:'0',
    //        format: 'yyyy-mm-dd hh:ii:ss',
    //        pickTime: false,
    //        autoclose:true,
    //        language:"cn",
    //        todayBtn:  1
    //    });
    //}
    //catch(err){
    //    console.log('无需时间控件')
    //}
    $('#searchSnNo').on('click',searchIt)
    $('#sendItout').on('click',submmitIt)
    //$('#reviewWhat').on('click',function(){
    //
    //})
})

var Mymodel={}
Mymodel.GetMessageList=ko.observableArray([]);
Mymodel.GetPaging=ko.observableArray([]);

changeSNSituation=function(it){
    $('#'+it.id.replace('SNSecond','')+'SNThird').val(it.value)
}

searchIt=function(){
    var param={}
    $('.searchGroupFirst').each(function(e){
        if(isNull($(this).val())==false){
            param[$(this).attr('id')]=$(this).val()
        }
    })
    var params = {
        url:appSocket+commmonUrlArray.findOrderByConditionsUrl+'?pageSize=1000000&&startAt=0&&'+decodeURIComponent($.param(param)).replace(/'/g,''),
        data:{},
        method:'get'
    }
    ajaxRequest(params,function(data){
        var validData=data.recordset
        var aimAtIt=$('#appendSF')
        aimAtIt.html('')
        if(validData!=''){
            for(var i in validData){
                //if(validData[i].FORDERSTATUS==undefined){
                //    validData[i].FORDERSTATUS=''
                //}
                try{validData[i].FLEASEBEGINTIME=new Date(validData[i].FLEASEBEGINTIME).Format('yyyy-mm-dd')}
                catch(err){

                }
                try{validData[i].FLEASEENDTIME=new Date(validData[i].FLEASEENDTIME).Format('yyyy-mm-dd')}
                catch(err){

                }
                try{validData[i].FTAKEAWAYTIME=new Date(validData[i].FTAKEAWAYTIME).Format('yyyy-mm-dd hh:ii')}
                catch(err){

                }
                var template='<tr><td class="table-checkbox"><label class="i-checks"><input type="checkbox" id="'+validData[i]._id+'"></label></td><td class="center">'+validData[i].FCHANNELSORDERNO+'</td><td class="center">'+validData[i].FEXPRESSRECIPIENT+'</td><td class="center">'+validData[i].FEXPRESSRECIPIENTTEL+'</td></tr>'
                aimAtIt.append(template)
            }
            totalValidData=validData.slice()
        }
    })
}

submmitIt=function(){
    var param={
        url:appSocket+commmonUrlArray.inWareHouseUrl,
        data:{
            "FDEVICELIST":deviceListArray,
            _id:lastValidData._id
        },
        method:'post'
    }
    ajaxRequest(param,function(data){
        if(data.status==200){
            alert('出库成功')
            window.location.reload()
        }
    })
}


ko.applyBindings(Mymodel);